<template>
  <div class="blog-list">
      <BlogItem 
        v-for="(blog, index) in blogs" 
        :key="blog.id" 
        :blog="blog" 
        :horizontal="index % 2 == 0 ? 'left' : 'right'"
        />
      <div v-show="showPlaceholder">
          <el-skeleton :rows="5" animated />
          <el-skeleton :rows="5" animated />
      </div>
      <el-pagination 
        class="pagination"
        color 
        layout="prev, pager, next" 
        :pager-count="5"
        v-model:current-page="currentPage"
        :hide-on-single-page="hideOnSinglePage"
        :total="total" 
        @current-change="handleCurrentChange"
      />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElLoading, ElSkeleton } from 'element-plus'
import BlogItem from '@/components/BlogItem.vue'

import { useBlogsStore } from '@/stores/blog.js'

const hideOnSinglePage = ref(true);

const blogsStore = useBlogsStore();
let blogs = ref([]);
let total = ref(0);
let pageSize = ref(5);
let currentPage = ref(1);

let showPlaceholder = ref(true);

onMounted(() => {
  blogsStore.articlePages(1, pageSize.value).then((result) => {
    setTimeout(() => {
      console.log(`当前页: 1`);
      console.log("首页分页数据：", result);
      showPlaceholder.value = false;
      total.value = result.total;
      blogs.value = blogsStore.sorted;
    }, 2000)
  }).catch(error => {
    console.log(error);
    ElMessage.error(error.message);
  })
})

const handleCurrentChange = (val) => {
  const loading = ElLoading.service({
    target: '.blog-list',
    lock: true,
  })
  blogsStore.articlePages(val, pageSize.value).then((result) => {
    setTimeout(() => {
      loading.close();
      console.log(`当前页: ${val}`);
      console.log("首页分页数据：", result);
      total.value = result.total;
      blogs.value = blogsStore.sorted;
      // ElMessage.success('加载成功 ' + result.list.length + " 条数据")
    }, 2000)
  }).catch(error => {
      loading.close();
      ElMessage.error(error.message);
  })
}

</script>

<style lang="scss" scoped>

.blog-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
    text-align: left;
  // background-color: slateblue;
}

.pagination {
    margin: 0 auto;
}

</style>